package cn.lizemin;

import cn.lizemin.entity.Product;
import cn.lizemin.entity.Products;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lzm
 * @version 1.0
 * @description: 测试将es的查询结果（JSON格式）转成对象
 * @date 2022/3/7 16:25
 */
@SpringBootTest
public class RestHighLevClientForObject {

    private final RestHighLevelClient restHighLevelClient;

    @Autowired
    public RestHighLevClientForObject(RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }

    /**
     * 将products对象转成json,然后放入 ES 中
     */
    @Test
    public void should_create_document() throws Exception {
        Products product = new Products();
        product.setId(2);
        product.setTitle("干吃面");
        product.setPrice(2.5);
        product.setDescription("小浣熊真好吃!");

        //首先将对象转成json，然后再将json发送给elasticsearch创建相关文档
        IndexRequest indexRequest = new IndexRequest("product");//这个是elasticsearch的映射
        indexRequest.id(product.getId().toString())
                .source(new ObjectMapper().writeValueAsString(product), XContentType.JSON);
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(indexResponse.status());

    }

    /**
     * 将elasticsearch返回的json格式的结果转成products对象
     * @throws IOException
     */
    @Test
    public void should_get_document() throws IOException {
        SearchRequest searchRequest = new SearchRequest("product");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.requireFieldMatch(false).field("description").preTags("<span style='color:red;'>").postTags("</span>");
        sourceBuilder
                .query(QueryBuilders.termQuery("description","好吃"))
                .from(0)
                .size(30)
                .highlighter(highlightBuilder);
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        System.out.println("符合条件总数: " + searchResponse.getHits().getTotalHits().value);
        System.out.println("获取文档最大分数: " + searchResponse.getHits().getMaxScore());

        SearchHit[] hits = searchResponse.getHits().getHits();
        List<Products> productList = new ArrayList<>();
        for (SearchHit hit : hits) {
            //1.获取返回结果的json，将其打印出来
            System.out.println(hit.getSourceAsString());//json
            //2.将结果中的json转成相应的对象
            Products product = new ObjectMapper().readValue(hit.getSourceAsString(), Products.class);
            //处理高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields.containsKey("description")){
                product.setDescription( highlightFields.get("description").fragments()[0].toString());
            }
            productList.add(product);
        }

        for (Products product : productList) {
            System.out.println("集合中所包含的对象： " + product);
        }
    }



}
